var Api = require('../../utils/api.js');
var erWeiMa = ['QR_CODE', 'DATA_MATRIX', 'PDF_417', 'WX_CODE'];

Page({
  onShareAppMessage(o) {},

  data: {
    inputShowed: true,
    inputVal: "",
    result: {
      "total": 0,
      "type": 0,
      "list": []
    },
    eatType: 0,
    eatRank: [],
    eatCurrent: []
  },

  onLoad(e) {
    var that = this;
    console.log("onload", e);
    if (e.eat_type) {
      this.setData({
        eatType: e.eat_type
      });
    }
    
    // 从后端获取排行榜数据
    wx.request({
      url: Api.eatRank(),
      method: 'GET',
      success: function(res) {
        console.log("获取排行榜数据成功:", res.data);
        if (res.data) {
          that.setData({
            eatRank: res.data
          });
        }
      },
      fail: function(err) {
        console.error("获取排行榜数据失败:", err);
      }
    });
    
    // 从后端获取最近食用数据
    wx.request({
      url: Api.eatCurrent(),
      method: 'GET',
      success: function(res) {
        console.log("获取最近食用数据成功:", res.data);
        if (res.data) {
          that.setData({
            eatCurrent: res.data
          });
        }
      },
      fail: function(err) {
        console.error("获取最近食用数据失败:", err);
      }
    });
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },

  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false,
      result: {
        "total": 0,
        "list": []
      }
    });
  },

  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },

  inputTyping: function (e) {
    var that = this;
    wx.showLoading({
      title: '搜索中',
    });
    const query = e.detail.value;
    console.log(`搜索: ${query}`);

    if (!query || query.trim() === '') {
      this.setData({
        inputVal: query,
        result: {
          total: 0,
          type: 0,
          list: []
        }
      });
      wx.hideLoading();
      return;
    }

    // 从后端搜索食物/运动
    wx.request({
      url: Api.search({ q: query }),
      method: 'GET',
      success: function(res) {
        console.log("搜索成功:", res.data);
        that.setData({
          inputVal: query,
          result: res.data || { total: 0, type: 0, list: [] }
        });
        wx.hideLoading();
      },
      fail: function(err) {
        console.error("搜索失败:", err);
        that.setData({
          inputVal: query,
          result: { total: 0, type: 0, list: [] }
        });
        wx.hideLoading();
      }
    });
  },

  scan(e) {
    console.log("扫描条形码");
    var that = this;
    wx.scanCode({
      success(res) {
        if (erWeiMa.indexOf(res.scanType) !== -1) {
          wx.showToast({
            title: "请扫描商品条形码",
            icon: "none"
          });
        } else {
          console.log("扫描结果:", res.result);
          // 调用后端扫码接口
          wx.request({
            url: Api.scanCode({ code: res.result }),
            method: 'GET',
            success: function(response) {
              console.log("扫码查询成功:", response.data);
              if (response.data) {
                that.setData({
                  inputVal: response.data.name || res.result,
                  result: response.data
                });
              }
            },
            fail: function(err) {
              console.error("扫码查询失败:", err);
              // 如果后端接口失败，尝试搜索条形码
              that.inputTyping({ detail: { value: res.result } });
            }
          });
        }
      },
      fail: function(err) {
        console.error("扫码失败:", err);
      }
    });
  }
});
